package com.ita.project1.dao.impl;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.ita.project1.dao.PersonDao;
import com.ita.project1.util.DbUtil;

import common.entity.Person;

public class PersonDaoImpl implements PersonDao {

	@Override
	public List<Person> showAllPerson() {
		List<Person> ps = new ArrayList<Person>();

		String sql = "select * from person";
		Connection con = null;
		PreparedStatement pst = null;
		ResultSet rs = null;
		con = DbUtil.connect();
		try {
			pst = con.prepareStatement(sql);
			rs = pst.executeQuery();
			Person p=null;
			while (rs.next()) {
				int pId = rs.getInt("pid");
				String pName = rs.getString("pname");
				Date date=rs.getDate("birthday");
				String tel=rs.getString("tel");
				int dId=rs.getInt("did");
				int salary=rs.getInt("salary");
				p=new Person(pName, date, tel, dId, salary);
				p.setpId(pId);
				ps.add(p);
			}
		} catch (SQLException e) {

			e.printStackTrace();
		} finally {
			DbUtil.free(con, pst, null);
		}
		return ps;
	}

	@Override
	public Person loadPerson(int id) {
		String sql = "select * from person where pid=?";
		Connection con = null;
		PreparedStatement pst = null;
		ResultSet rs = null;
		con = DbUtil.connect();
		Person p=null;
		try {
			pst = con.prepareStatement(sql);
			pst.setInt(1, id);
			rs = pst.executeQuery();
			if(rs.next()) {
				int pId = rs.getInt("pid");
				String pName = rs.getString("pname");
				Date date=rs.getDate("birthday");
				String tel=rs.getString("tel");
				int dId=rs.getInt("did");
				int salary=rs.getInt("salary");
				p = new Person(pName, date, tel, dId, salary);
				p.setpId(pId);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DbUtil.free(con, pst, null);
		}
		return p;
	}

}
